/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package logica;

import dao.LecturaDAO;
import dao.SustratoDAO;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JCheckBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.ProgressMonitor;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.CategoryLabelPositions;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.ValueMarker;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.xy.XYSeries;
import org.jfree.data.xy.XYSeriesCollection;
import org.jfree.ui.LengthAdjustmentType;
import org.jfree.ui.RectangleAnchor;
import org.jfree.ui.TextAnchor;
import vista.JDialogProgressBar;
import vista.panel.InterfazHistoricos;

/**
 *
 * @author Elias Mendoza
 */
public class Historicos extends Thread {
  
  

  private TableModel modeloTabla;
  private Object[] fila;
  private String sustrato;
  private Date[] fecha;
  private String[] sensores;
  InterfazHistoricos p;
 
  
  
  public Historicos(InterfazHistoricos principal) {
    this.p = principal;
    
    
  }

  public String getSustrato() {
    return sustrato;
  }

  public void setSustrato(String sustrato) {
    this.sustrato = sustrato;
  }

  public void inicializarTablaSensoresYBarraProgreso(JTable tablaSensores) {
    modeloTabla = new DefaultTableModel() {

      Class[] types = new Class[]{java.lang.Character.class, java.lang.Boolean.class};

      @Override
      public Class getColumnClass(int columnIndex) {
        return types[columnIndex];
      }
    };

    tablaSensores.setModel(modeloTabla);
    ((DefaultTableModel) modeloTabla).setColumnIdentifiers(new Object[]{"sensor", "select"});
    fila = new Object[2];

    p.jProgressBarConsultaBD.setMinimum(0);
    p.jProgressBarConsultaBD.setStringPainted(true);
    p.jProgressBarConsultaBD.setValue(0);
    
  }

  public void addFila(char sensor, boolean check) {
    fila[0] = sensor;
    fila[1] = true;
    ((DefaultTableModel) modeloTabla).addRow(fila);
  }

  public void llenaTablaSensores(String nombreSustrato) {
    SustratoDAO sustratoDAO = new SustratoDAO();
    int numGrupos = sustratoDAO.numGrupos(nombreSustrato) * 4 + 65;
    JCheckBox check = new JCheckBox();
    for (int i = 65; i < numGrupos; i++) {
      char sensor = (char) i;

      addFila(sensor, true);
    }
  }

  public void consultaSensoresActivos() {
    sensores = new String[modeloTabla.getRowCount()];
    char caracter = 0;
    for (int i = 0; i < modeloTabla.getRowCount(); i++) {
      boolean activo = (Boolean) modeloTabla.getValueAt(i, 1);
      if (activo) {
        caracter = (Character) modeloTabla.getValueAt(i, 0);
        sensores[i] = caracter + "";
      }
    }
  }

  public void determinaTipoReporte() {
    if (p.jComboBoxSeleccion.getSelectedItem().toString().equals("Dia")) {
      fecha = new Date[1];
      fecha[0] = p.jDateChooserFechaInicial.getDate();
    }
    if (p.jComboBoxSeleccion.getSelectedItem().toString().equals("Periodo")) {
      fecha = new Date[2];
      fecha[0] = p.jDateChooserFechaInicial.getDate();
      fecha[1] = p.jDateChooserFechaFinal.getDate();
    }
  }

  public void iniciaOperacion() {
    consultaSensoresActivos();
    determinaTipoReporte();
    if(p.jRadioButtonGasto.isSelected())
      if (p.jComboBoxSeleccion.getSelectedItem().toString().equals("Dia")) {
        new GraficaGasto(p, fecha,"dia").start();
      }else
        if (p.jComboBoxSeleccion.getSelectedItem().toString().equals("Periodo")) {
          new GraficaGasto(p, fecha,"periodo").start();
        }
    if(p.jRadioButtonSensores.isSelected())
      new GraficaSensores(p, fecha, sensores).start();
    
  }
}

//*****************************************************************************************

class GraficaSensores extends Thread {

  float optimo;
  InterfazHistoricos p;
  Date[] fecha;
  String[] sensores;
  ProgressMonitor pMonitor;

  public GraficaSensores(InterfazHistoricos p, Date[] fecha, String[] sensores) {
    this.p = p;
    this.fecha = fecha;
    this.sensores = sensores;
    pMonitor = new ProgressMonitor(p,"Progreso", "Consultando",0, 100);
    pMonitor.setMillisToPopup( 0 );
  }

  @Override
  public void run() {
    graficaHumedad();
  }

  private void graficaHumedad() {
    SustratoDAO s = new SustratoDAO();
    optimo = s.valorReferenciaOptimo(p.jComboBoxSustrato.getSelectedItem().toString());
    float promedio;
    List lista;


    String sustrato = p.jComboBoxSustrato.getSelectedItem().toString();

    LecturaDAO l = new LecturaDAO();
    DefaultCategoryDataset dataset1 = new DefaultCategoryDataset();
    pMonitor.setMaximum(sensores.length+20);
    int incr = 1;
    for (int i = 0; i < sensores.length; i++) {
      pMonitor.setProgress(incr++);
      pMonitor.setNote(i+"%");
      if(pMonitor.isCanceled())
          break;
//      p.jProgressBarConsultaBD.setValue(incr++);
      System.out.println("procesando sensor " + sensores[i]);
      if (sensores[i] != null) {
        Iterator ite = l.consultaLecturaSensores(sustrato, fecha, sensores[i].toString().toLowerCase()).iterator();
        while (ite.hasNext()) {
          Object[] obj = (Object[]) ite.next();
          for (int inc = 0; inc < obj.length; inc++) {
            promedio = (float) ((Double) obj[0] * 100 / optimo);
            String humedad = String.format("%.2f", promedio);
            dataset1.addValue(Float.parseFloat(humedad), "sensor:" + incr + "[" + sensores[i].toString() + "]", obj[2] + "-" + obj[1]+"Hr");
          }
        }
      }
      
    }


    JFreeChart chart = ChartFactory.createLineChart("Sensores de " + sustrato, "Lectura", "Hora", dataset1, PlotOrientation.VERTICAL, true, true, false);
    CategoryPlot plot = (CategoryPlot) chart.getCategoryPlot();

    ValueAxis valueaxis = plot.getRangeAxis();
    valueaxis.setRange(0.0D, 150D);
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.BLACK);
    plot.setRangeGridlinePaint(Color.MAGENTA);
    plot.setRangeCrosshairPaint(Color.BLUE);
    plot.setRangeZeroBaselinePaint(Color.RED);
    CategoryAxis categoryaxis = plot.getDomainAxis();
    categoryaxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    
    categoryaxis.setCategoryMargin(0.0);


    determinaCondiciones(plot);




    ChartPanel grafico = new ChartPanel(chart);
    p.accion.aderirPanel(grafico, p.jPanelContenedorGrafica);
//    p.jProgressBarConsultaBD.setValue(incr+20);
    pMonitor.setProgress(incr+20);

  }

  public void determinaCondiciones(CategoryPlot plot) {
    if (p.jCheckBoxOptimo.isSelected()) {
      ValueMarker valuemarker = new ValueMarker(100);
      valuemarker.setLabel("Optimo");
      propiedadesMarker(valuemarker);
      plot.addRangeMarker(valuemarker);
    }
    if (p.jCheckBoxLimSuperior.isSelected()) {
      ValueMarker valuemarker = new ValueMarker(115);
      valuemarker.setLabel("Lim. Superior");
      propiedadesMarker(valuemarker);
      plot.addRangeMarker(valuemarker);
    }
    if (p.jCheckBoxLimInferiror.isSelected()) {
      ValueMarker valuemarker = new ValueMarker(75);
      valuemarker.setLabel("Lim. Inferior");
      propiedadesMarker(valuemarker);
      plot.addRangeMarker(valuemarker);
    }
  }

  public void propiedadesMarker(ValueMarker valuemarker) {
    valuemarker.setLabelOffsetType(LengthAdjustmentType.EXPAND);
    valuemarker.setPaint(Color.MAGENTA);
    valuemarker.setStroke(new BasicStroke(1.0F));
    valuemarker.setLabelFont(new Font("SansSerif", 0, 10));
    valuemarker.setLabelPaint(Color.black);
    valuemarker.setLabelAnchor(RectangleAnchor.TOP_LEFT);
    valuemarker.setLabelTextAnchor(TextAnchor.BOTTOM_LEFT);
  }
}


//*****************************************************************************************

class GraficaGasto extends Thread {

   float gasto;
  InterfazHistoricos p;
  Date[] fecha;
  String tipo;
  ProgressMonitor pMonitor;
  public GraficaGasto(InterfazHistoricos p, Date[] fecha, String tipo) {
    this.p = p;
    this.fecha = fecha;
    this.tipo = tipo;
    pMonitor = new ProgressMonitor(p,"Progreso", "Consultando",0, 100);
    pMonitor.setMillisToPopup( 0 );
  }

  @Override
  public void run() {
      seleccionDeGrafica();
  }
  private void seleccionDeGrafica(){
    if(tipo.equals("dia")){
      graficaGastoDia();
    }
    if(tipo.equals("periodo")){
      graficaGastoPeriodo();
    }
  }

  private void graficaGastoDia() {

    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    LecturaDAO lecturaDAO = new LecturaDAO();
    List gastoByGrupoByHora = lecturaDAO.consultaGastoAcumuladoByDia(p.jComboBoxSustrato.getSelectedItem().toString(), fecha[0]);
    pMonitor.setMaximum(gastoByGrupoByHora.size()+1);
    int incr = 1;
    for (Object obj : gastoByGrupoByHora) {
      pMonitor.setProgress(incr++);
      pMonitor.setNote(incr+"%");
      if(pMonitor.isCanceled())
          break;
      Object[] array = (Object[]) obj;
      int hora = (Integer) array[1];
      float prom = (float) ((Double) array[0] * 1);
      String format = String.format("%.2f", prom);
      dataset.addValue(Float.parseFloat(format),"gasto", hora+" Hrs");
      System.out.println("array[0]="+array[0]+" array[1]="+array[1]);
    }
    creaGrafica(dataset);
    pMonitor.setProgress(incr+1);

  }

  public void graficaGastoPeriodo(){
    DefaultCategoryDataset dataset = new DefaultCategoryDataset();
    LecturaDAO lecturaDAO = new LecturaDAO();
    List gastoByPeriodo = lecturaDAO.consultaGastoAcumuladoByPeriodo(p.jComboBoxSustrato.getSelectedItem().toString(), fecha);
   
    pMonitor.setMaximum(gastoByPeriodo.size()+1);
    int incr = 1;
    for (Object obj : gastoByPeriodo) {
      pMonitor.setProgress(incr++);
      pMonitor.setNote(incr+"%");
      if(pMonitor.isCanceled())
          break;
      Object[] array = (Object[]) obj;
      float prom = (float) ((Double) array[1] * 1);
      String format = String.format("%.2f", prom);
      dataset.addValue(Float.parseFloat(format),"gasto",array[0].toString());
      System.out.println("array[0]="+array[0]+" array[1]="+array[1]);
    }
    creaGrafica(dataset);
    pMonitor.setProgress(incr+1);
  }
  
  public void creaGrafica(DefaultCategoryDataset dataset){
    JFreeChart chart = ChartFactory.createLineChart("Gasto de agua de " + p.jComboBoxSustrato.getSelectedItem().toString()+" (Dia)", "Hora", "Gasto", dataset, PlotOrientation.VERTICAL, true, true, false);
    CategoryPlot plot = (CategoryPlot) chart.getCategoryPlot();
    
    ValueAxis valueaxis = plot.getRangeAxis();
//    valueaxis.setRange(0.0D, 100D);
    plot.setBackgroundPaint(Color.WHITE);
    plot.setDomainGridlinePaint(Color.BLACK);
    plot.setRangeGridlinePaint(Color.MAGENTA);
    plot.setRangeCrosshairPaint(Color.BLUE);
    plot.setRangeZeroBaselinePaint(Color.RED);
    CategoryAxis categoryaxis = plot.getDomainAxis();
    categoryaxis.setCategoryLabelPositions(CategoryLabelPositions.UP_45);
    
    categoryaxis.setCategoryMargin(0.0);
    
    ChartPanel grafico = new ChartPanel(chart);
    p.accion.aderirPanel(grafico, p.jPanelContenedorGrafica);
  }
  
  
}
